package com.guaoran.source.curatorzk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/13 18:09
 */
public class RegisterCenterImpl implements IRegisterCenter {
    private CuratorFramework curatorFramework = ZookeeperConfig.initCuratorFramework();


    @Override
    public void register(String serviceName, String serviceAddress) {
        String servicePath = ZookeeperConfig.ZK_REGISTER_PATH + "/" + serviceName;
        //判断服务节点是否存在
        try {
            if(curatorFramework.checkExists().forPath(servicePath) == null){
                //服务节点不存在，则创建持久化服务节点
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath,"0".getBytes());
                System.out.println("创建服务持久化节点成功："+servicePath);
            }
            //创建服务地址临时节点
            String serviceAddressPath = servicePath + "/" + serviceAddress;
            String tempNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(serviceAddressPath, "1".getBytes());
            System.out.println("创建临时节点成功："+serviceAddressPath + "-->" + tempNode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            curatorFramework.close();
        }
    }
}
